package com.github.binarylei.curator.watcher;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.junit.Test;

/**
 * PathChildrenCache 子节点监听
 *
 * @author: leigang
 * @version: 2018-04-06
 */
public class ZkCuratorWatcher2 {

    private static final String CONNECT_ADDR = "127.0.0.1:2181";
    private static final int SEESION_OUTTIME = 5 * 1000;

    @Test
    public void test() throws Exception {
        //1. 重试策略：初试时间为1s，重试10次
        ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(1000, 10);

        //2. 通过工厂创建连接
        CuratorFramework cf = CuratorFrameworkFactory.builder()
                .connectString(CONNECT_ADDR)
                .sessionTimeoutMs(SEESION_OUTTIME)
                .retryPolicy(retryPolicy)
                .build();

        //3. 开启连接
        cf.start();

        //4. 建立一个 PathChildrenCache 缓存，第三个参数为是否接受节点数据内容，如果为 false 则不接受
        PathChildrenCache cache = new PathChildrenCache(cf, "/curator", true);
        //5. 在初始化的时候就进行缓存监听
        cache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);

        cache.getListenable().addListener(new PathChildrenCacheListener() {
            // 监听子节点变量，新建、修改、删除
            @Override
            public void childEvent(CuratorFramework cf, PathChildrenCacheEvent event) throws Exception {
                switch (event.getType()) {
                    case CHILD_ADDED:
                        System.out.println("CHILD_ADDED：" + event.getData().getPath());
                        break;
                    case CHILD_UPDATED:
                        System.out.println("CHILD_UPDATED：" + event.getData().getPath());
                        break;
                    case CHILD_REMOVED:
                        System.out.println("CHILD_REMOVED：" + event.getData().getPath());
                        break;
                    default:
                        break;
                }
            }
        });

        cf.create().creatingParentsIfNeeded().forPath("/curator/c1", "c1".getBytes());
        cf.create().creatingParentsIfNeeded().forPath("/curator/c2", "c2".getBytes());

        Thread.sleep(1000);
        cf.setData().forPath("/curator/c1", "c1-update".getBytes());

        cf.delete().guaranteed().deletingChildrenIfNeeded().forPath("/curator");

        cf.close();
    }
}
